import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { message, Switch } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { DATA_ENTRY, AdvancedSearch, TableC, FormItemLayout, ExportC } from '../../../comps';
import myStyle from './index.less';
import colors from '../../../css/colors';
import HistoryModalC from './historyModal';
import upPng from '../../../assets/commom/up_arrow.png';
import downPng from '../../../assets/commom/down_arrow.png';
import SetColumns from './SetColumns';

@connect(({ ratingmonitoringM, globalM, loading }) => ({
  ratingmonitoringM,
  globalM,
  loading,
}))
export default class TabSearch extends PureComponent {
  state = {
    timeOutGap: 500,
    currentPage: 1, // news当前页码
    numInPage: 10, // 每页数量
    total: 0, // 总条数
    searchData: {
      startDate: moment().subtract(1, 'year').add(1, 'day'),
      endDate: moment(),
      adjustDirection: '-1',
      analysisType: '0',
    }, // 查询条件
    secReset: false, // 是否点击重置按钮
    modalData: undefined, // 点击的评级id
    columns: undefined, // 表头
    dataSource: undefined, // 表格数据
    bondList: [], // 债券代码List
    selectComCode: undefined,
    mainBodyList: [], // 主体列表
    isSplite: true, // 默认穿透
    analysisType: '0', // 分析类型
    isMerge: true, // 穿透资产默认true合并
  };

  componentDidMount() {
    this.props.onRef(this);
    this.queryTableList();
    this.onBondSearch('');
    // 查表头信息
    if (this.props.type == 2) {
      this.props.dispatch({
        type: 'ratingmonitoringM/queryShowCol',
        payload: {
          tab: this.props.type,
          type: this.props.colType,
        },
      });
    }
  }

  UNSAFE_componentWillReceiveProps(nextPorps) {
    // 中债的列 跟分析类型的选择有关
    if (nextPorps.colType != this.props.colType && this.props.type == 2) {
      this.props.dispatch({
        type: 'ratingmonitoringM/queryShowCol',
        payload: {
          tab: this.props.type,
          type: nextPorps.colType,
        },
      });
    }
  }

  refresh = (code, name) => {
    const { type } = this.props;
    this.onBondSearch(name);
    const obj = { ...this.state.searchData };
    obj.bondId = code;
    this.setState(
      {
        searchData: obj,
      },
      () => {
        this[`searchRef${type}`]?.props?.form.setFieldsValue({
          [`bondId${type}`]: code,
        });
        this.queryTableList();
      },
    );
  };

  // key value转换
  showValue = (arr, value) => {
    if (!arr.length) return '--';
    let text = value;
    arr.forEach((item) => {
      if (item.code === value) text = item.value;
    });
    return text || '--';
  };

  // 查询表格数据
  queryTableList = () => {
    const { dispatch, type } = this.props;
    const { searchData, numInPage, currentPage } = this.state;
    this.setState({
      columns: undefined, // 表头
      dataSource: undefined, // 表格数据
      loadingStatus: true,
    });
    const apiParams = {
      ...searchData,
      currentPage,
      numInPage,
      startDate: moment(searchData?.startDate).format('YYYY-MM-DD'),
      endDate: moment(searchData?.endDate).format('YYYY-MM-DD'),
    };
    if (type == 2) {
      // 中债 分析类型不同列默认值不同
      this.props.changeCol(apiParams.analysisType == 2 ? 'Implied_Rating' : 'Implied_Rating_1');
    }
    if (type == '0') {
      dispatch({
        // 查询主体评级监控
        type: 'ratingmonitoringM/queryMainList',
        payload: { ...apiParams },
        callback: (type, data) => {
          if (type == 'success') {
            data.dataSource && data.dataSource.map((item, key) => (item.key = key));
            this.setState({
              columns: data.columns || [],
              dataSource: data.dataSource || [],
              currentPage: data.pageInfo?.currentPage,
              total: data?.pageInfo?.total,
            });
          } else {
            this.setState({
              columns: [],
              dataSource: [],
              total: 0,
            });
          }
          this.setState({
            loadingStatus: false,
          });
        },
      });
    } else if (type == '1') {
      dispatch({
        // 获取债券评级监控列表
        type: 'ratingmonitoringM/queryBondRatingList',
        payload: { ...apiParams },
        callback: (type, data) => {
          if (type == 'success') {
            data.dataSource && data.dataSource.map((item, key) => (item.key = key));
            this.setState({
              columns: data.columns || [],
              dataSource: data.dataSource || [],
              currentPage: data.pageInfo?.currentPage,
              total: data.pageInfo?.total || 0,
            });
          } else {
            this.setState({
              columns: [],
              dataSource: [],
              total: 0,
            });
          }
          this.setState({
            loadingStatus: false,
          });
        },
      });
    } else {
      apiParams.isSplite = this.state.analysisType == '2' ? (this.state.isSplite ? '0' : '1') : undefined;
      apiParams.isMerge = this.state.analysisType == '2' ? (this.state.isMerge ? '0' : '1') : undefined;
      dispatch({
        // 获取中债隐含评级监控列表
        type: 'ratingmonitoringM/queryList',
        payload: { ...apiParams },
        callback: (type, data) => {
          if (type == 'success') {
            data.dataSource && data.dataSource.map((item, key) => (item.key = key));
            this.setState({
              columns: data.columns || [],
              dataSource: data.dataSource || [],
              currentPage: data.pageInfo.currentPage,
              total: data?.pageInfo?.total,
            });
          } else {
            this.setState({
              columns: [],
              dataSource: [],
              total: 0,
            });
          }
          this.setState({
            loadingStatus: false,
          });
        },
      });
    }
  };

  // 展示表格
  showTable = () => {
    const {
      ratingmonitoringM: { columnsInfo },
      globalM: {
        dataDictionary: { ENDOFPERIODRATEPROSPECT = [], ADJUSTDIRECTION_OUT = [], RATERANGESTART_END = [] },
      },
    } = this.props;
    const { currentPage, numInPage, columns, dataSource, loadingStatus } = this.state;
    if (this.props.type == 2) {
      const columns2 = _.cloneDeep(columnsInfo[this.props.type].columns);
      this.newColumns = columns2.filter((item) => item.display == true);
    }
    const newCols = this.props.type == 2 ? this.newColumns : columns;
    if (newCols && newCols.length && newCols[newCols.length - 1].key != 'operate') {
      const operate = {
        title: this.props.type == 2 ? '历史详情' : '历史和持仓',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        fixed: 'right',
        width: 120,
        operates: [
          {
            title: '查看',
            onClick: (record, index) => {
              this.showHistory(record);
            },
          },
        ],
      };
      newCols.push(operate);
    }
    newCols &&
      newCols.map((item) => {
        if (item.key == 'comName') {
          item.type = 'maxContent';
          item.width = 250;
        }
        if (item.key == 'adjustTime' || item.key == 'lastRateDate' || item.key == 'expiryDate') {
          item.type = 'date';
        }

        if (item.key == 'endOfPeriodRateProspect' || item.key == 'begianOfPeriodRateProspect') {
          item.render = (text, record) => {
            return this.showValue(ENDOFPERIODRATEPROSPECT, text);
          };
        }

        if (item.key == 'adjustDirection') {
          item.render = (text, record) => {
            const temp = this.showValue(ADJUSTDIRECTION_OUT, text);
            const styleObj = {
              marginLeft: ' 8px',
              verticalAlign: 'top',
              paddingTop: '5px',
            };
            const styleObj1 = {
              marginLeft: ' 12px',
              verticalAlign: 'top',
              paddingTop: '5px',
            };
            if (text == '0') {
              return (
                <span style={{ color: colors.debtAndProfit.text[0] }}>
                  {temp} <img src={upPng} style={styleObj}></img>
                </span>
              );
            } else if (text == '1') {
              return (
                <span style={{ color: colors.debtAndProfit.text[1] }}>
                  {temp}
                  <img src={downPng} style={styleObj1}></img>
                </span>
              );
            } else {
              return temp;
            }
          };
        }
      });
    return (
      <div style={{ marginTop: '20px' }}>
        <TableC
          columns={newCols}
          dataSource={dataSource}
          rowKey='key'
          current={currentPage}
          hidePage={true}
          pageSize={numInPage}
          scroll={{ x: 'max-content' }}
          loading={loadingStatus}
        />
        <div className='pageBtn'>
          <span
            onClick={() => {
              this.pageChange('pre');
            }}
            className={currentPage == 1 ? 'disabledBtn' : ''}
          >
            上一页{' '}
          </span>
          <span
            onClick={() => {
              this.pageChange('next');
            }}
            className={this.state.total <= numInPage * currentPage ? 'disabledBtn' : ''}
          >
            下一页
          </span>
        </div>
      </div>
    );
  };

  // 页码跳转
  pageChange = (changeType) => {
    const { currentPage, numInPage } = this.state;
    if (this.state.total <= numInPage * currentPage && changeType == 'next') return;
    if (changeType == 'pre') {
      if (currentPage == 1) return;
    }
    this.setState(
      {
        currentPage: changeType == 'pre' ? currentPage - 1 : currentPage + 1,
      },
      () => {
        this.queryTableList();
      },
    );
  };

  // 查看历史持仓
  showHistory = (row) => {
    this.setState({
      visibleModal: true,
      modalData: row,
    });
  };

  // 父组件点击重置按钮 调用该方法
  resetForm = () => {
    this.setState({
      secReset: false,
      selectComCode: undefined,
      bondList: [], // 清空数据
    });
  };

  // 债券模糊查询
  onBondSearch = (e) => {
    const { dispatch } = this.props;
    const { timeOutGap, selectComCode } = this.state;
    this.timer ? clearTimeout(this.timer) : '';
    this.timer = setTimeout(() => {
      dispatch({
        type: 'ratingmonitoringM/queryBondId',
        payload: {
          code: selectComCode?.length ? selectComCode : undefined,
          // code: undefined,
          value: e,
        },
        callback: (res) => {
          if (res) {
            if (res.code == 0) {
              const tempData = res.data.dataSource.slice(0, 100) || [];
              tempData.forEach((item) => {
                item.title = `${item.value}-${item.title}`;
              });
              this.setState({
                bondList: tempData,
              });
            } else {
              message.error(res.msg || '查询债券代码下拉列表失败!');
            }
          } else {
            message.error('查询债券代码下拉列表失败!');
          }
        },
      });
    }, timeOutGap);
  };

  // 主体名称模糊搜索
  queryComcode = (e) => {
    const that = this;
    const { dispatch } = this.props;
    const { timeOutGap } = this.state;
    if (e) {
      that.comTimer ? clearTimeout(that.comTimer) : '';
      that.comTimer = setTimeout(() => {
        dispatch({
          type: 'ratingmonitoringM/queryComcode',
          payload: {
            name: e,
          },
          callback: (val, data) => {
            if (val == e) {
              that.setState({
                mainBodyList: data,
              });
            }
          },
        });
      }, timeOutGap);
    }
  };

  comCodeOnChange = (e) => {
    const { type } = this.props;
    if (type == 0) return;
    this.setState(
      {
        selectComCode: e || undefined,
      },
      () => {
        this[`searchRef${type}`]?.props?.form.setFieldsValue({
          [`bondId${type}`]: undefined,
        });
        this.onBondSearch('');
      },
    );
  };

  // 穿透开关
  changeSwitch = (e) => {
    this.setState(
      {
        isSplite: e,
        currentPage: '1',
      },
      () => this.queryTableList(),
    );
  };

  // 资产是否合并
  handleCMSwitch = (e) => {
    // console.log('e', e);
    this.setState(
      {
        isMerge: e,
        currentPage: '1',
      },
      () => this.queryTableList(),
    );
  };

  // 分析类型变化
  analysisTypeChange = (e) => {
    this.setState({
      analysisType: e,
    });
  };

  // 获取导出参数
  getParmas = () => {
    const { dispatch, type } = this.props;
    const { searchData, selectComCode } = this.state;
    const apiParams = {
      ...searchData,
      startDate: moment(searchData.startDate).format('YYYY-MM-DD'),
      endDate: moment(searchData.endDate).format('YYYY-MM-DD'),
    };
    if (selectComCode) apiParams.comCode = selectComCode.join(',');
    if (type == '0') {
      // 主体评级监控
    } else if (type == '1') {
      // 债券评级监控
    } else {
      // 中债隐含评级监控
      if (this.state.analysisType == '2') {
        apiParams.isSplite = this.state.isSplite ? '0' : '1';
        apiParams.isMerge = this.state.isMerge ? '0' : '1';
        // console.log(777, apiParams);
      }
    }
    return apiParams;
  };

  render() {
    const that = this;
    const {
      loading,
      type,
      ratingmonitoringM: { checkedKeysInfo },
      globalM: {
        dataDictionary: { COMPANY_ANALYSIS_TYPE = [], ENDOFPERIODRATEPROSPECT = [], ADJUSTDIRECTION = [], RATERANGESTART_END = [] },
      },
    } = this.props;
    const { analysisType, visibleModal, modalData, bondList, mainBodyList, isSplite, isMerge } = this.state;

    const searchProps = {
      dataSource: [
        {
          dataIndex: 'comCode',
          title: '主体名称',
          type: DATA_ENTRY.SELECT,
          dataSource: (mainBodyList || []).map((item) => {
            return { ...item };
          }),
          placeholder: '请输入',
          allowClear: true,
          isMultiple: true,
          maxTagCount: 0,
          filterOption: false,
          onChange: this.comCodeOnChange,
          onSearch: (e) => {
            that.queryComcode(e);
          },
          loading: loading.effects['ratingmonitoringM/queryComcode'] === true,
        },
        {
          dataIndex: 'analysisType',
          title: '分析类型',
          type: DATA_ENTRY.SELECT,
          dataSource: COMPANY_ANALYSIS_TYPE.map((item) => {
            return {
              value: item.code,
              title: item.value,
            };
          }),
          initialValue: '0',
          onChange: this.analysisTypeChange,
        },
        {
          hide: type === '0',
          dataIndex: `bondId${type}`,
          title: '债券代码',
          type: DATA_ENTRY.SELECT,
          // type: DATA_ENTRY.SECURITIESCODE,
          // codeType: codeType.zq,
          dataSource: bondList,
          allowClear: true,
          formItemLayout: FormItemLayout,
          optionTitle: true,
          onSearch: (e) => {
            this.onBondSearch(e);
          },
          filterOption: false,
        },
        {
          dataIndex: ['startDate', 'endDate'],
          title: '调整时间',
          type: DATA_ENTRY.RANGEDATE,
          formItemLayout: FormItemLayout,
          initialValue: [moment().subtract(1, 'week').add(1, 'day'), type == '2' ? moment().subtract(1, 'day') : moment()],
          hasDataED: type == '2' ? moment().subtract(1, 'day') : undefined,
        },
        {
          hide: type === '2',
          dataIndex: `endOfPeriodRateProspect${type}`,
          title: '期末评级展望',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          optionTitle: true,
          formItemLayout: FormItemLayout,
          dataSource: ENDOFPERIODRATEPROSPECT.map((item) => {
            return {
              value: item.code,
              title: item.value,
            };
          }),
        },
        {
          dataIndex: `adjustDirection${type}`,
          title: '调整方向',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          initialValue: '-1',
          formItemLayout: FormItemLayout,
          dataSource: ADJUSTDIRECTION.map((item) => {
            return {
              value: item.code,
              title: item.value,
            };
          }),
        },
        {
          dataIndex: [`rateRangeStart${type}`, `rateRangeEnd${type}`],
          title: '评级区间',
          type: DATA_ENTRY.RANGESELECT,
          dataSource: [
            RATERANGESTART_END.map((item) => {
              return {
                value: item.code,
                title: item.value,
              };
            }),
            RATERANGESTART_END.map((item) => {
              return {
                value: item.code,
                title: item.value,
              };
            }),
          ],
        },
      ],
      onQuery: (e) => {
        const obj = {
          comCode: e.comCode,
          analysisType: e.analysisType,
          bondId: e[`bondId${type}`] ? e[`bondId${type}`] : undefined,
          adjustDirection: e[`adjustDirection${type}`] ? e[`adjustDirection${type}`] : undefined,
          endOfPeriodRateProspect: e[`endOfPeriodRateProspect${type}`] ? e[`endOfPeriodRateProspect${type}`] : undefined,
          rateRangeEnd: e[`rateRangeEnd${type}`] ? e[`rateRangeEnd${type}`] : undefined,
          rateRangeStart: e[`rateRangeStart${type}`] ? e[`rateRangeStart${type}`] : undefined,
          endDate: e.endDate,
          startDate: e.startDate,
        };

        this.setState(
          {
            searchData: obj,
            secReset: false,
            currentPage: 1,
          },
          () => {
            if ((e.rateRangeStart == undefined && e.rateRangeEnd == undefined) || (e.rateRangeStart && e.rateRangeEnd)) {
              if (e.rateRangeStart) {
                const tempStart = RATERANGESTART_END.filter((item) => item.code == e.rateRangeStart);
                const tempEnd = RATERANGESTART_END.filter((item) => item.code == e.rateRangeEnd);
                if (tempStart[0].orderIdx > tempEnd[0].orderIdx) {
                  this.queryTableList(); // 点击查询按钮
                } else {
                  message.warning('评级区间必须由低到高!');
                }
              } else {
                this.queryTableList(); // 点击查询按钮
              }
            } else {
              message.warning('评级区间请填写完整!');
            }
          },
        );
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchData: {
            startDate: moment().subtract(1, 'year').add(1, 'day'),
            endDate: moment(),
            adjustDirection: '-1',
            analysisType: '0',
            selectComCode: undefined,
            analysisType: '2',
            isSplite: true,
            isMerge: false,
          },
        });
      },
      onRef: (ref) => (this[`searchRef${type}`] = ref),
    };
    return (
      <div style={{ minHeight: '450px' }}>
        <div>
          <AdvancedSearch {...searchProps} />
        </div>
        {type == 2 ? (
          <div style={{ display: 'flex', justifyContent: ' flex-end', alignItems: 'center', marginTop: '15px' }}>
            {analysisType == 2 ? (
              <div className={myStyle.mySwitch}>
                <span>持仓穿透</span>
                <Switch checked={isSplite} onChange={this.changeSwitch} />
                <div style={{ display: this.state.isSplite ? 'flex' : 'none' }}>
                  <span>穿透资产是否合并</span>
                  <Switch checked={isMerge} onChange={this.handleCMSwitch} />
                </div>
              </div>
            ) : null}
            <div style={{ marginRight: '10px' }}>
              <ExportC url={'gateway/instrument-server/rating/exportImpliedRatingList'} search={this.getParmas()} disabled={!this.state.dataSource?.length} />
            </div>
            <div>
              <SetColumns type={this.props.type} colType={this.props.colType} checkedKeysInfo={checkedKeysInfo} />
            </div>
          </div>
        ) : null}
        {this.showTable()}
        {visibleModal ? (
          <HistoryModalC
            type={type}
            modalData={modalData}
            visibleModal={visibleModal}
            triggerVisible={(e) => {
              this.setState({ visibleModal: e });
            }}
          />
        ) : null}
      </div>
    );
  }
}
